#include <memory>
#include <iostream>
using std::cout;
using std::endl;
using std::weak_ptr;
using std::shared_ptr;

class Point
{
public:
    Point(int ix = 0, int iy = 0)
    : _ix(ix)
    , _iy(iy)
    {   cout << "Point(int,int)" << endl;   }

    ~Point() {  cout << "~Point()" << endl; }

    void print() const
    {   cout << "(" << _ix << "," << _iy << ")" << endl;}

private:
    int _ix;
    int _iy;
};

void test0()
{
    weak_ptr<Point> wp;
    {
        shared_ptr<Point> sp(new Point(11, 12));
        cout << "sp.use_count():" << sp.use_count() << endl;

        wp = sp;//赋值操作不会导致引用计数加1
        cout << "sp.use_count():" << sp.use_count() << endl;
        cout << "wp.use_count():" << wp.use_count() << endl;

        cout << "wp.expired(): " << wp.expired() << endl;

        //对weak_ptr进行提升
        shared_ptr<Point> sp2 = wp.lock();
        if(sp2) {
            cout << "sp2.use_count():" << sp2.use_count() << endl;
            sp2->print();
        } else {
            cout << "所托管的对象已经被销毁了,提升失败" << endl;
        }
    }

    cout << endl;
    cout << "wp.expired(): " << wp.expired() << endl;
    //在语句块之外，此时weak_ptr所托管的对象已经被销毁了
    shared_ptr<Point> sp2 = wp.lock();
    if(sp2) {
        cout << "sp2.use_count():" << sp2.use_count() << endl;
        sp2->print();
    } else {
        cout << "所托管的对象已经被销毁了,提升失败" << endl;
    }
}


int main()
{
    test0();
    return 0;
}

